<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card style="margin-top: 15px">
      <!-- 警告区 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区 -->
      <el-row style="margin-top: 15px">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selOption"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab  -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态属性 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnAble">添加参数</el-button>
          <el-table :data="manyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.att_vals"
                  :key="i"
                  closable
                  @close="CloseTage(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 可以添加的tag事件 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="medium"
                  @click="adit(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="min"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnAble">添加参数</el-button>
          <el-table :data="onlyTableData" style="width: 100%">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="静态属性"
            ></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="medium"
                  @click="adit(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="min"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加商品分类对话框 -->
    <el-dialog
      title="'添加'+'titleText"
      :visible.sync="dialogFormVisible"
      @close="addClose"
    >
      <el-form
        :model="addForm"
        ref="addRef"
        label-width="100px"
        rules="addRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改商品分类 对话框 -->
    <el-dialog
      title="'添加'+'titleText"
      :visible.sync="dialogFormVisible"
      @close="addClose"
    >
      <el-form
        :model="aditForm"
        ref="aditRef"
        label-width="100px"
        rules="aditRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="aditForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="aditParams">取 消</el-button>
        <el-button type="primary" @click="aditParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框双向绑定
      selOption: [],
      // 级联选择框配置项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // moren
      activeName: 'many',
      // 动态表格的数据
      manyTableData: [],
      // 静态参数的数据
      onlyTableData: [],
      // 对话框是否可见
      dialogFormVisible: false,
      addForm: [],
      addRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
      aditForm: [],
      aditRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    // this.getCateList()
  },
  methods: {
    //   获取商品分类列表数据据
    async getCateList() {
      const { data: res } = await this.$http.post('categores')
      if (res.meta.state !== 200) {
        return this.$message.error('获取商品分类是数据失败')
      }
      this.cateList = res.data
    },
    // 级联选择框发生变化
    async handleChange() {
      this.getParamsData()
    },
    // tab页签点击事件
    handleTabClick() {
      this.getParamsData()
    },
    // 获取参数的列表
    async getParamsData() {
      // 如果选中的数组长度不是3，则不是三级分类
      if (this.selOption.length !== 3) {
        this.selOption = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attribute`,
        { params: { sel: this.activeName } }
      )
      res.data.forEach((item) => {
        item.att_vals = item.att_vals.split(' ')
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        item.inputvalue = ''
      })
      if (res.meta.state !== 200) {
        return this.$message.error('获取分类数失败')
      }
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听对话框的关闭事件
    addClose() {
      this.$$refs.addRef.resetFields()
    },
    // 确认添加商品参数
    addParams() {
      this.$refs.addRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categores/${this.cateId}/attibutes`,
          {
            attr_name: this.addForm.attr_name,
            att_sel: this.activeName,
          }
        )
        if (res.mate.status !== 200) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.dialogFormVisible = false
        this.getCateList()
      })
    },
    // 编辑 商品参数
    // eslint-disable-next-line camelcase
    async adit(attr_id) {
      const { dat: res } = await this.$http.get(
        // eslint-disable-next-line camelcase
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.editForm = res.data
      this.dialogFormVisible = true
    },
    // 确认编辑
    aditParams() {
      this.$$refs.editRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}`,
          {
            attr_name: this.editForm.attr_name,
            att_sel: this.activeName,
          }
        )
        if (res.meat.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.dialogFormVisible = false
      })
    },
    // 删除参数
    async delParams() {
      const confirm = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 用户取消删除操作
      if (confirm !== 'confirm') {
        return this.$message.error('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categores/${this.cateId}`)
      if (res.meta.status !== 200) {
        return this.message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // tag 输入款或按钮 失去焦点或按下enter键触发事件
    async handleInputConfirm(row) {
      // 输入内容无效
      if (row.inputvalue.trim().length === 0) {
        row.input = ''
        row.inputVisible = false
        return
      }
      // 输入内容有效
      row.attr_vals.push(row.inputvalue.trim())
      row.inputvalue = ''
      row.inputVisible = false
      // 发起请求 保存
      this.saveTag(row)
    },
    // 保存tag 修改
    async saveTag(row) {
      const { data: res } = await this.$http.put(
        `categores/#{this.cateid}/attibute/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          att_sel: row.att_sel,
          att_vals: row.att_vals.join(''),
        }
      )
      if (res.meta.state) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    },
    // tag 从按钮转变为输入框
    showInput() {
      this.inputVisible = true
      // 输入框自动获取焦点
      //  $nextTick方法的作用：页面上元素被重新渲染后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // tag标签 事件
    async CloseTage(i, row) {
      row.attr_vals.split(i, 1)
      this.saveTag()
    },
  },
  computed: {
    isBtnAble() {
      if (this.selOption.lenge !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类id
    cateId() {
      if (this.selOption.length === 3) {
        return this.selOption[2]
      }
      return null
    },
    // 判断动态参数或静态属性
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style  scoped>
.input-new-tag {
  width: 120px;
}
</style>
